package com.simonall.netty.resolver.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.simonall.netty.resolver.HttpParamResolver;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.util.CharsetUtil;

/**
 * Body Param Resolver
 * 
 * @author simonall
 */
@SuppressWarnings("unchecked")
public class BodyParamResolver implements HttpParamResolver {

	@Override
	public Map<String, List<String>> resolver(HttpRequest request) {
		if (request instanceof FullHttpRequest) {
			FullHttpRequest fullReq = (FullHttpRequest) request;
			ByteBuf content = fullReq.content();
			if (content != null && content.capacity() > 0) { // body need is JSON
				String json = content.toString(CharsetUtil.UTF_8);
				String link = MapUtil.join(JSONUtil.toBean(json, HashMap.class), "&", "=");
				return new QueryStringDecoder(link).parameters();
			}
		}
		return MapUtil.newHashMap();
	}

	@Override
	public <T> T resolver(HttpRequest request, Class<T> clazz) {
		Map<String, Object> source = new HashMap<String, Object>();
		resolver(request).entrySet().forEach(entry -> {
			if (entry.getValue().size() == 1) {
				source.put(entry.getKey(), entry.getValue().get(0));
			} else {
				source.put(entry.getKey(), entry.getValue());
			}
		});
		return BeanUtil.toBeanIgnoreError(source, clazz);
	}

}
